package com.luntan.school.web.servlet;

import com.luntan.school.model.User;
import com.luntan.school.service.UserService;
import com.luntan.school.service.impl.UserServiceImpl;
import com.luntan.school.util.Md5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        User user = userService.login(account, Md5Util.md5(password)); // 注意：密码需要先进行MD5加密
        if (user != null) { //登陆成功
            HttpSession session = request.getSession(); // 获取session
            session.setAttribute("user", user);

//            request.setAttribute("page", "index.jsp");
//            request.setAttribute("pageName", "首页");
//            request.getRequestDispatcher("delay_jump.jsp").forward(request, response);

            String rootPath = request.getContextPath(); //获取项目根目录的绝对路径
            response.sendRedirect(rootPath + "/login.jsp"); //注意设置Servlet重定向的正确路径
        } else { //登陆失败
            request.setAttribute("error", "账户或密码错误！");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }

    }
}
